import random
import sounddevice as sd
import soundfile as sf

def record_audio(fs, duration):
    print("请击打桌面...")

    # 录制音频
    recording = sd.rec(int(fs * duration), samplerate=fs, channels=1)
    sd.wait()

    return recording

def save_audio(recording, filename, fs):
    # 保存录制的音频到文件
    sf.write(filename, recording, fs)

def play_audio(filename):
    # 播放保存的音频文件
    data, fs = sf.read(filename, dtype="float32")
    sd.play(data, fs)
    sd.wait()

def play_game():
    print("欢迎来到剪刀石头布游戏！")

    while True:
        # 录制音频
        fs = 44100  # 采样率
        duration = 1  # 录制时长（秒）
        recording = record_audio(fs, duration)

        # 保存音频文件
        filename = "recording.wav"
        save_audio(recording, filename, fs)

        # 播放音频文件
        play_audio(filename)

        # 模拟电脑选择
        computer_choice = random.choice(["剪刀", "石头", "布"])

        # 判断用户选择
        user_choice = None
        if recording.mean() < -0.01:
            user_choice = "剪刀"
        elif recording.mean() > 0.01:
            user_choice = "布"
        else:
            user_choice = "石头"

        # 打印选择结果和调试信息
        print(f"用户选择: {user_choice}")
        print(f"用户输入的计算结果（调试信息）: {recording.mean()}") 

        # 判断胜负
        if user_choice == computer_choice:
            print("结果: 平局")
        elif (user_choice == "剪刀" and computer_choice == "布") or (user_choice == "石头" and computer_choice == "剪刀") or (user_choice == "布" and computer_choice == "石头"):
            print("结果: 用户胜利")
        else:
            print("结果: 电脑胜利")

        # 询问是否再玩一局
        play_again = input("是否再玩一局？(按下回车键继续，输入其他内容退出): ")
        if play_again.lower() != "":
            break

play_game()
